import backtrader as bt

# 成交量与价格背离检测
class VolumePriceDivergenceStrategy(bt.Strategy):
    params = (
        ('divergence_threshold', 0.1),  # 背离阈值
    )

    def __init__(self):
        self.order = None

    def next(self):
        if len(self.data) > 1:
            prev_volume = self.data.volume[-1]
            current_volume = self.data.volume[0]
            volume_change = (current_volume - prev_volume) / prev_volume

            prev_close = self.data.close[-1]
            current_close = self.data.close[0]
            price_change = (current_close - prev_close) / prev_close

            if price_change > 0 and volume_change < -self.params.divergence_threshold:
                if self.position:
                    self.order = self.sell()
            elif price_change < 0 and volume_change > self.params.divergence_threshold:
                if self.position:
                    self.order = self.sell()
                else:
                    self.order = self.buy()

    def notify_order(self, order):